import "./index.scss";
import {
  Divider,
  Input,
  Form,
  Button,
  Select,
  Table,
  Switch,
  Space,
  Pagination,
  Modal,
  message 
} from "antd";
import {useRef,useState, useEffect} from 'react'
import { getMemberInfo } from "../../../utils/getMemberInfo";
import { searchMemberInfo } from "../../../utils/searchMember";
import { updateMemberInfo } from "../../../utils/updateMemberInfo";
const Student = () => {
  const [selectionType, setSelectionType] = useState("checkbox");
  const columns = [
    {
      title: "序号",
      dataIndex: "user_id",
    },
    {
      title: "成员账号",
      dataIndex: "user_email",
    },
    {
      title: "姓名",
      dataIndex: "user_name",
    },
    {
      title: "手机号",
      dataIndex: "user_phone",
    },
    {
      title: "邮箱",
      dataIndex: "user_email",
    },
    {
      title: "角色",
      dataIndex: "user_type",
    },
    {
      title: "创建时间",
      dataIndex: "user_creattime",
      render: (text, record) => {
        console.log(text, record);
        const dateStr = record.user_creattime;
        const date = new Date(dateStr);
        date.setDate(date.getDate() + 1);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate() - 1).padStart(2, "0");
        const formattedDate = `${year}-${month}-${day}`; // "2023-04-10"

        return <span>{formattedDate}</span>;
      },
    },
    {
      title: "是否启用",
      dataIndex: "user_enable",
      align: "center",
      render: (text, record, index) => {
        return (
          <Switch
            defaultChecked={record.user_enable}
            disabled
            checked={record.user_enable}
          

          />
        );
      },
    },
    
   
    {
      title: "操作",
      align: "center",
      render: (text, record, index) => {
        return (
          <Space>
            <a onClick={()=>{
              upDate(record)
            }}>编辑</a>
            {/* <a onClick={()=>{
               delRole(record,index)
            }}>删除</a> */}
          </Space>
        );
      },
    },
  ];
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        "selectedRows: ",
        selectedRows
      );
    },
    getCheckboxProps: (record) => ({
      name: record.name,
    }),
  };
  const getMember = () => {
    getMemberInfo()
      .then((res) => {
        console.log(res.data, "res");
        const list = res.data.map((item) => ({ ...item, key: item.user_id }));
        console.log(list, "list");
        setDataList(list);

      })
      .catch((err) => {
        console.log(err, "err");
      });
  };
  const searchMember =(values)=>{
    searchMemberInfo(values)
    .then((res) => {canData
      console.log(res.data, "res,searchMemberInfo");
      const list = res.data.map((item) => ({ ...item, key: item.user_id }));
      console.log(list, "list,searchMemberInfo");
      setDataList(list);

    })
    .catch((err) => {
      console.log(err, "err");
    });
  }
  const updateMember=(data)=>{
    updateMemberInfo(data)
    .then((res) => {
      console.log(res.data, "updateMemberInfo");
      getMember() 

    })
    .catch((err) => {
      console.log(err, "err");
    });
  }
  const [dataList, setDataList] = useState([]);
  const [delData,setDelData]=useState([])
  const [canData,setCanData]=useState([])
  const data = [...dataList];
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isOpen,setIsopen]=useState(false)
  const [old,setOld]=useState([])
  // const ok = (values) => {
  //   if (values.user_enable == undefined) {
  //     values.user_enable = true;
  //   }
  //   console.log("onFinishok", values);
  //   console.log(addForm, "addform");
  //   if (values) {
  //     const now = new Date();
  //     const year = now.getFullYear();
  //     const month = String(now.getMonth() + 1).padStart(2, "0");
  //     const day = String(now.getDate()).padStart(2, "0");
  //     const hours = String(now.getHours()).padStart(2, "0");
  //     const minutes = String(now.getMinutes()).padStart(2, "0");
  //     const seconds = String(now.getSeconds()).padStart(2, "0");

  //     const datetime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  //     console.log(datetime,'datetime');
  //     let list=[]
  //     list.push(values)
  //     let listData=list.map((item) => ({ ...item, user_creattime: datetime }))
  //     console.log(listData,'66');
  //     AddRole(listData)
  //     addForm.current.resetFields();
  //     setIsModalOpen(false)

  //   }
  // };
  // const FailedOk = (values) => {
  //   console.log("onFinishFailed:", values);

  // };
  const upOk = (values) => {
    console.log(values,'是大苏打');
    if (values.user_enable == undefined) {
      values.user_enable = true;
    }
    console.log("onFinishok", values);
    console.log(addForm, "addform");
    if (values) {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");

      const datetime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      console.log(datetime,'datetime');
      let list=[]
      list.push(values)
      console.log(old.user_id,'old');
      let listData=list.map((item) => ({ ...item, user_id: old.user_id }))
      console.log(listData,'6666');
      updateMember(listData)
      addForm.current.resetFields();
      setIsopen(false)
     message.success({
      type: 'success',
      content: '修改成功!'
    });
    }
  };
  const cancel = (values) => {
    console.log("onFinishFailed:", values);

  };
  const addBtn = () => {
    console.log(111);

    setIsModalOpen(true);
  };
  const { TextArea } = Input;
  const onChange = (e) => {
    console.log("Change:", e.target.value);
  };
  const onChange2 = (e) => {
    console.log("Change:", e.target.value);
  };
  const onSwitch = (checked) => {
    console.log(`switch to ${checked}`);
  };
  const onSwitch2 = (checked) => {
    console.log(`switch to ${checked}`);
  };
  const [value, setValue] = useState(null);
  const [value2,setValue2]=useState(null)
  const handleFocus = () => {
    setValue("");
  };
  const handleFocus2 = () => {
    setValue2("");
  };
  const addForm = useRef();
  const delRole=(data)=>{
    console.log('赖总');
    console.log(data,'delRole');
    delInfo(data)

  }
  let list=[]
  const upDate=(data,index)=>{
    console.log('路总');
    console.log(data,'编辑');
    setOld(data)
    list=data
    setCanData(data)
    console.log(canData,'编辑表格');
    setIsopen(true);


  }
  useEffect(() => {
    getMember();
    
   }, []);
  useEffect(() => {
    console.log(old, '编辑');
    console.log(canData, '编辑表格');
  
  }, [old, canData]);
  const { Option } = Select;
  const layout = {
    labelCol: {
      span: 8,
    },
    wrapperCol: {
      span: 16,
    },
  };
  const tailLayout = {
    wrapperCol: {
      offset: 8,
      span: 16,
    },
  };
  const formRef = useRef(null);
  const onGenderChange = (value) => {
    switch (value) {
      case 'male':
        formRef.current?.setFieldsValue({
          note: 'Hi, man!',
        });
        break;
      case 'female':
        formRef.current?.setFieldsValue({
          note: 'Hi, lady!',
        });
        break;
      case 'other':
        formRef.current?.setFieldsValue({
          note: 'Hi there!',
        });
        break;
      default:
        break;
    }
  };
  const onFinish = (values) => {
    console.log(values,'查询');
    searchMember(values)
  };

  const reset=()=>{
   console.log('重置');
   getMember()
   formRef.current?.resetFields();
  }
  return (
    <div>
       <h1>角色管理</h1>
       <Divider />
       <div className={"first"}>
        <div className={"first_1"}>
           <span>筛选查询</span>
        </div>
        <div className={"first_2"}>
        <Form
      {...layout}
      ref={formRef}
      name="control-ref"
      onFinish={onFinish}
      style={{
        maxWidth: 600,
      }}
    >
      <Form.Item
        className="keywords"
        name="keywords"
        label="关键词"
        rules={[
          {
          },
        ]}

      >
        <Input placeholder="姓名"  style={{width:"250px",height:"40px"}}/>
      </Form.Item>
      <Form.Item
       className="role"
        name="role"
        label="角色"
        rules={[
          {
          },
        ]}
      >
        <Select
          placeholder="请选择角色"
          onChange={onGenderChange}
          allowClear
          style={{width:"250px",height:"40px"}}
        >
          <Option value="administrator">管理员</Option>
          <Option value="member">成员</Option>
          <Option value="user">用户</Option>
        </Select>
      </Form.Item>
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
      >
        {({ getFieldValue }) =>
          getFieldValue('gender') === 'other' ? (
            <Form.Item
              name="customizeGender"
              label="Customize Gender"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input />
            </Form.Item>
          ) : null
        }
      </Form.Item>
      <Form.Item {...tailLayout} className="bottom">
        <Button type="primary" htmlType="button"  className="btn1" onClick={()=>{
           reset()
        }}>
          重置
        </Button>
        <Button htmlType="submit" 
         className="btn2" >
          筛选
        </Button>
       
      </Form.Item>
    </Form>
        </div>
       </div>
       {/* <Button
        className={"addBtn"}
        onClick={() => {
          addBtn();
        }}
      >
        添加
      </Button> */}
      <Table
        className={"table"}
        pagination={false}
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        columns={columns}
        dataSource={data}
      />
      <Pagination
        className={"Pagination"}
        total={1}
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `共 ${total} 页`}
      />
      <>
        {/* <Modal title="添加成员" open={isModalOpen} footer={null}>
          <Form
            className={"form1"}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            onFinish={ok}
            onFinishFailed={FailedOk}
            autoComplete="off"
            ref={addForm}
            initialValues={delData}
          >
            <Form.Item
              label="成员账号"
              name="user_email"
              rules={[{ required: true, message: "成员账号不能为空" }]}
            >

              <Input placeholder="此为登录使用账号" />
            </Form.Item>
            <Form.Item
              label="姓名"
              name="user_name"
              rules={[{ required: true, message: "姓名不能为空" }]}
            >
              <Input  />
             
            </Form.Item>
            <Form.Item
            
              label="手机号"
              name="user_phone"
              rules={[{ required: true, message: "手机号不能为空" }]}
              
            >
              <Input />
             
            </Form.Item>
            <Form.Item
              label="邮箱"
              name="user_email"
              rules={[{ required: true, message: "邮箱不能为空" }]}
            >
              <Input />
             
            </Form.Item>
            <Form.Item
              label="角色"
              name="user_type"
              rules={[{ required: true, message: "角色不能为空" }]}
            >
               <Select
          placeholder="请选择角色"
          onChange={onGenderChange}
          allowClear
          style={{width:"250px",height:"40px"}}
        >
          <Option value="administrator">管理员</Option>
          <Option value="member">成员</Option>
          <Option value="user">用户</Option>

        </Select>
             
            </Form.Item>
                <Form.Item
              label="登录密码"
              name="user_pwd"
              rules={[{ required: true, message: "密码不能为空" }]}
            >
              <Input type="password"/>
             
            </Form.Item>
            <Form.Item
              label="确认密码"
              name="user_pwd"
              rules={[{ required: true, message: "密码不能为空" }]}
            >
              <Input type="password"/>
             
            </Form.Item>
            <Form.Item
              label="备注信息"
              name="user_message"
            >
              <TextArea
                showCount
                maxLength={50}
                onChange={onChange}
                style={{ height: "120px" }}
                value={value}
                onFocus={handleFocus}
              />
            </Form.Item>
            <Form.Item
              label="是否启用"
              name="roleEnable"
              valuePropName="checked"
            >
              <Switch defaultChecked onChange={onSwitch} value={value} />
            </Form.Item>
            <Form.Item className="btn">
              <Button type="primary" htmlType="submit" 
              >
                提交
              </Button>
              <Button
                htmlType="button"
                style={{ marginLeft: "20px" }}
                onClick={() => {
                   setIsModalOpen(false);
                   
                }}
              >
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>canData
      </>
      <> */}
        <Modal title="编辑成员" open={isOpen} footer={null} destroyOnClose={true}>
          <Form
            className={"form2"}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            onFinish={upOk}
            onFinishFailed={cancel}
            autoComplete="off"
            ref={addForm}
            initialValues={canData}
          >
           <Form.Item
              label="成员账号"
              name="user_email"
              rules={[{ required: true, message: "成员账号不能为空" }]}
            >

              <Input />
            </Form.Item>
            <Form.Item
              label="姓名"
              name="user_name"
              rules={[{ required: true, message: "姓名不能为空" }]}
            >
              <Input />
             
            </Form.Item>
            <Form.Item
              label="手机号"
              name="user_phone"
              rules={[{ required: true, message: "手机号不能为空" }]}
            >
              <Input />
             
            </Form.Item>
            <Form.Item
              label="邮箱"
              name="user_email"
              rules={[{ required: true, message: "邮箱不能为空" }]}
            >
              <Input />
             
            </Form.Item>
            <Form.Item
              label="角色"
              name="user_type"
              rules={[{ required: true, message: "角色不能为空" }]}
            >
               <Select
          placeholder="请选择角色"
          onChange={onGenderChange}
          allowClear
          style={{width:"250px",height:"40px"}}
        >
          <Option value="administrator">管理员</Option>
          <Option value="member">成员</Option>
          <Option value="user">用户</Option>

        </Select>
             
            </Form.Item>
                <Form.Item
              label="旧密码"
              name="user_pwd"
              rules={[{ required: true, message: "密码不能为空" }]}
            >
              <Input.Password />
             
            </Form.Item>
            <Form.Item
              label="新密码"
              name="user_newPwd"
              rules={[{ required: true, message: "密码不能为空" }]}
            >
              <Input.Password/>
             
            </Form.Item>
            <Form.Item
              label="是否启用"
              name="user_enable"
              valuePropName="checked"
            >
              <Switch defaultChecked onChange={onSwitch} value={value} />
            </Form.Item>
            <Form.Item className="btn">
              <Button type="primary" htmlType="submit" 
              >
                提交
              </Button>
              <Button
                htmlType="button"
                style={{ marginLeft: "20px" }}
                onClick={() => {
                  setIsopen(false);
                   
                }}
              >
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
        </>
    </div>
  );
};

export default Student;
